package com.ruoyi.college.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.college.domain.*;
import com.ruoyi.college.domain.Class;
import com.ruoyi.college.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课程与班级关联Controller
 * 
 * @author ruoyi
 * @date 2025-08-26
 */
@Controller
@RequestMapping("/college/courseClass")
public class CourseClassController extends BaseController
{
    private String prefix = "college/courseClass";

    @Autowired
    private ICourseClassService courseClassService;

    @Autowired
    private ICourseTeacherService courseTeacherService;

    @Autowired
    private IClassService classService;

    @Autowired
    private ICourseArrangementService courseArrangementService;

    @Autowired
    private ITeacherService teacherService;

    @RequiresPermissions("college:courseClass:view")
    @GetMapping()
    public String courseClass(ModelMap mmap)
    {
        List<CourseArrangement> courseArrangements = courseArrangementService.selectCourseArrangementList(new CourseArrangement());
        mmap.put("courseArrangements", courseArrangements);
        List<Teacher> teachers = teacherService.selectTeacherList(new Teacher());
        mmap.put("teachers", teachers);
        List<Class> classes = classService.selectClassList(new Class());
        mmap.put("classes", classes);
        return prefix + "/courseClass";
    }

    /**
     * 查询课程与班级关联列表
     */
    @RequiresPermissions("college:courseClass:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CourseClass courseClass)
    {
        startPage();
        List<CourseClass> list = courseClassService.selectCourseClassList(courseClass);
        return getDataTable(list);
    }

    @GetMapping("/getClassesByArrangementId")
    @ResponseBody
    public AjaxResult getClassesByArrangementId(Long arrangementId)
    {
        List<CourseClass> list = courseClassService.getClassesByArrangementId(arrangementId);
        return AjaxResult.success(list);
    }

    /**
     * 导出课程与班级关联列表
     */
    @RequiresPermissions("college:courseClass:export")
    @Log(title = "课程与班级关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CourseClass courseClass)
    {
        List<CourseClass> list = courseClassService.selectCourseClassList(courseClass);
        ExcelUtil<CourseClass> util = new ExcelUtil<CourseClass>(CourseClass.class);
        return util.exportExcel(list, "课程与班级关联数据");
    }

    /**
     * 新增课程与班级关联
     */
    @RequiresPermissions("college:courseClass:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        List<CourseTeacher> courseTeachers = courseTeacherService.selectCourseTeacherList(new CourseTeacher());
        // 核心逻辑：按courseId去重，保留每个courseId的第一条数据
        List<CourseTeacher> distinctCourses = courseTeachers.stream()
                // 以courseId为键，CourseTeacher对象为值
                .collect(Collectors.toMap(
                        CourseTeacher::getCourseId,  // 键：courseId（唯一标识）
                        course -> course,            // 值：当前对象
                        (existing, replacement) -> existing  // 冲突策略：保留已有对象（第一条）
                ))
                // 转换为List
                .values().stream()
                .collect(Collectors.toList());
        mmap.put("courseTeachers", distinctCourses);
        List<Class> classes = classService.selectClassList(new Class());
        mmap.put("classes", classes);
        return prefix + "/add";
    }

    /**
     * 新增保存课程与班级关联
     */
    @RequiresPermissions("college:courseClass:add")
    @Log(title = "课程与班级关联", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CourseClass courseClass)
    {
        List<Long> classIds = courseClass.getClassIds();
        //List<CourseClass> courseClasses = new ArrayList<>();
        for (Long classId : classIds) {
            courseClass.setClassId(classId);
            courseClassService.insertCourseClass(courseClass);
        }
        return toAjax(1);
    }

    /**
     * 修改课程与班级关联
     */
    @RequiresPermissions("college:courseClass:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        List<CourseTeacher> courseTeachers = courseTeacherService.selectCourseTeacherList(new CourseTeacher());
        // 核心逻辑：按courseId去重，保留每个courseId的第一条数据
        List<CourseTeacher> distinctCourses = courseTeachers.stream()
                // 以courseId为键，CourseTeacher对象为值
                .collect(Collectors.toMap(
                        CourseTeacher::getCourseId,  // 键：courseId（唯一标识）
                        course -> course,            // 值：当前对象
                        (existing, replacement) -> existing  // 冲突策略：保留已有对象（第一条）
                ))
                // 转换为List
                .values().stream()
                .collect(Collectors.toList());
        mmap.put("courseTeachers", distinctCourses);
        List<Class> classes = classService.selectClassList(new Class());
        mmap.put("classes", classes);
        CourseClass courseClass = courseClassService.selectCourseClassById(id);
        mmap.put("courseClass", courseClass);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程与班级关联
     */
    @RequiresPermissions("college:courseClass:edit")
    @Log(title = "课程与班级关联", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CourseClass courseClass)
    {
        return toAjax(courseClassService.updateCourseClass(courseClass));
    }

    /**
     * 删除课程与班级关联
     */
    @RequiresPermissions("college:courseClass:remove")
    @Log(title = "课程与班级关联", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(courseClassService.deleteCourseClassByIds(ids));
    }
}
